<template>
  <div class="setting-customer flex-y" v-loading="loading">
    <div class="setting-customer-header">
      <div class="flex-1">
        <!-- <button type="button" class="btn btn-text setting-back-btn" @click="back"><i class="iconfont icon-arrow-left"></i> 返回</button>
        <span class="setting-header-text">|</span> -->

        <span v-if="!pageButtonSetGray">{{ $t('common.form.setting.setCustomField') }}</span>

        <div class="flex-x flex-1 jus-center setting-header-box" v-if="pageButtonSetGray">
          <div class="setting-header-item-box" :class="[nowType === 'form' ? 'is-checked' : '']" @click="nowType = 'form'">{{ $t('projectManage.setting.workLog.tip5') }}</div>
          <div class="setting-header-item-box" :class="[nowType === 'button' ? 'is-checked' : '']" @click="nowType = 'button'">{{ $t('setting.buttonSet.text1') }}</div>
        </div>
      </div>
      <base-button type="primary" native-type="submit" :disabled="pending" @event="confirm">{{ $t('common.base.save') }}</base-button>
    </div>
    <div class="setting-customer-design" v-show="nowType === 'form'">
      <form-design v-model="fields" :max="maxField" mode="customer" :isOpenRegister="isOpenRegister" :templateId="templateId" :templateName="templateName"> </form-design>
    </div>
    <div class="flex-1" v-show="nowType === 'button'">
      <ButtonSet ref="buttonSetDom" v-if="pageButtonSetGray" :mode="ButtonGetTriggerModuleEnum.Customer"></ButtonSet>
    </div>
  </div>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import platform from '@src/platform';
import { getCustomerFields, customerSaveFields } from '@src/api/CustomerApi';
import { getMapping } from '@src/api/ProductV2Api';
/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';

import { getConfig } from '@src/api/ProductV2Api';
/* model */
import { ConnectorBizTypeIdEnum } from '@src/modules/connector/model';
import ButtonSet from '@src/component/compomentV2/buttonSet/index.vue';
import { t } from '@src/locales';
import { ButtonGetTriggerModuleEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum';
import { packToHttpByHttpDataForButonList, packToLocalByHttpDataForButonList } from '@src/component/compomentV2/buttonSet/common';
import { setDataForButtonSet, getDataForButtonSet } from '@src/api/SystemApi';
import { havePageButtonSetGray } from '@src/util/grayInfo';

export default {
  name: 'setting-customer-fields-view',
  mixins: [fieldMixin, FormDesignMixin, ThemeMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: true,
      fields: [],
      pending: false,
      maxField: this.initData.fieldNum,
      isOpenRegister: false,
      nowType: 'form',
      ButtonGetTriggerModuleEnum,
      pageButtonSetGray: havePageButtonSetGray(),
    };
  },
  components: {
    ButtonSet,
  },
  computed: {
    templateId() {
      return ConnectorBizTypeIdEnum.Customer;
    },
    templateName() {
      return this.$t('common.connector.customerForm');
    },
  },
  mounted() {
    // const currentTabId = window.frameElement.dataset.id;
    // if (window.frameElement) {
    //   const currentTabId = window.frameElement.dataset.id;
    //   platform.setTabTitle({
    //     id: currentTabId,
    //     title:'附加组件设置'
    //   })
    // }
    // this.setFieldDesignHeight();

    // this.computedFormWidthAndHeight('setting-customer');
    // window.addEventListener('resize', this.resizeHandler);
    this.getFieldsInfoReq();
    this.isOpenRegisterCheck();
    if (this.pageButtonSetGray) {
      this.getButtonSetData();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
  },
  methods: {
    isOpenRegisterCheck() {
      getConfig({
        configCode: ['PRODUCT_REGISTRATION'],
      }).then(res => {
        if (res.errorCode === 0) {
          this.isOpenRegister = !!res?.data[0]?.isOpen;
        }
      });
    },
    back() {
      window.parent.frameHistoryBack(window);
    },
    resizeHandler(event) {
      this.computedFormWidthAndHeight('setting-customer');
    },
    async submit() {
      try {
        let fields = FormUtil.toField(this.fields);

        fields.forEach(item => {
          item.tableName = 'customer';
          if (item.setting && item.setting.isAuthorization === void 0) {
            item.setting.isAuthorization = false;
          }
        });

        let message = FormUtil.validate(fields);
        if (!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;
        let result = await customerSaveFields(fields);
        if (result.status == 0) {
          platform.notification({
            type: 'success',
            title: this.$t('common.base.success'),
            message: this.$t('common.base.moduleFieldUpdateSuccess', { module: this.$t('common.form.type.customer') }),
          });
          return this.pending = false;
        }

        platform.notification({
          type: 'error',
          title: this.$t('common.base.moduleFieldUpdateError', { module: this.$t('common.form.type.customer') }),
          message: result.message,
        });
      } catch (error) {
        console.error(error);
      }

      this.pending = false;
    },
    //获取客户表单属性列表
    getFieldsInfoReq() {
      getCustomerFields({ isFromSetting: true })
        .then(res => {
          const { status, data, message } = res;
          if (status == 0) {
            const fields = data || [];

            const sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
            this.fields = FormUtil.toFormField(sortedFields);
          }

          this.loading = false;
          return getMapping({
            destTable: 'customer',
            sourceTable: 'register',
          });
        })
        .then(r => {
          if (r.status == 0) {
            for (let item of this.fields) {
              r.data.forEach(i => {
                if (item.fieldName == i.destFieldName) {
                  item.fieldMappingForm = {
                    sourceTable: 'register',
                    sourceField: i.sourceFieldName,
                    sourceFieldDisplayName: i.sourceFieldDisplayName,
                    registerFieldFlag: i.registerFieldFlag,
                  };
                }
              });
            }
          }
        })
        .catch(error => {
          console.log(error, 'error');
          this.loading = false;
        });
    },
    async confirm() {
      if (this.nowType === 'button') {
        const value = await this.$refs.buttonSetDom.getValue();
        if (!value) return;
        this.pending = true;
        const btnList = packToHttpByHttpDataForButonList(value);
        setDataForButtonSet({
          module: ButtonGetTriggerModuleEnum.Customer,
          buttonList: btnList,
          moduleId: 1,
        }).then(res => {
          if (res.status === 0) {
            platform.notification({
              type: 'success',
              title: this.$t('common.base.success'),
              message: this.$t('common.modal.MODIFY_SUCCESS')
            })
            return this.getButtonSetData();
          } else {
            platform.notification({
              type: 'error',
              title: this.$t('common.base.moduleFieldUpdateError', { module: this.$t('common.form.type.customer') }),
              message: res.message,
            });
          }
        }).finally(()=>{
          this.pending = false;
        });;
      } else {
        this.submit();
      }
    },
    getButtonSetData() {
      getDataForButtonSet({
        module: ButtonGetTriggerModuleEnum.Customer,
        moduleId: 1,
        showArea: 'list',
        isEdit: true,
      }).then(res => {
        if (res.status === 0) {
          const arr = packToLocalByHttpDataForButonList(res.data);
          this.$refs.buttonSetDom.initArr(arr);
        }
      });
    },
  },
};
</script>

<style lang="scss">
html,
body {
  height: 100%;
}

.setting-customer {
  height: 100%;
  overflow-y: hidden;
  background: #f5f5f5;
}

.setting-header-text {
  margin-right: 12px;
}

.setting-customer-header {
  margin: 12px 12px 0 12px;
  padding: 10px;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  border-bottom: 1px solid #f4f7f5;
}

.setting-customer-design {
  padding: 12px;
  height: calc(100% - 53px);
}

.setting-back-btn {
  i.iconfont {
    line-height: 12px;
    font-size: 12px;
  }
}
</style>
<style lang="scss" scoped>
@import '@src/modules/setting/customer/chooseType.scss';
</style>
`
